# -*- coding: utf-8 -*-
import sys

import pytest
import shutil

from common.writer import writer
from common.reader import get_reader, ReadExcel
from time import sleep
import os

from key_word.appKeys import App
from key_word.webKeys import Web



class Conf:
    def __init__(self):
        # self.run_status = 1  # 暂不传参运行
        # self.br = None  # 暂不传参运行
        # self.flag = False
        self.n = 1
        self.story_row = []
        self.null_row_num_before_assert = []
        self.i = []
        self.sheet = ''
        # 设置分组信息
        self.feature = '测试项目'
        self.feature_idx = 0
        self.story = '测试分组'
        self.story_idx = 0
        # 保存一个模块里面所有的用例
        self.cases = []
        #初始化关键字对象
        self.obj = None

        # 记录运行的sheet和用例的序号
        self.s_idx = 1
        self.c_idx = 1

        #记录运行的用例类型
        self.case_type = 'web'

    def runCase(self, case_file='./cases/web-shopingshop.xlsx', res_file='./cases/result-web-shopingshop.xlsx'):
        # self.br = br#暂不传参运行
        # writer = Writer()
        writer.copy_open(case_file, res_file)
        # 获取excel里面的用例，处理成列表，并且运行
        # reader = get_reader(res_file)
        # print("reader为", reader)
        # writer = get_writer(case_file, res_file)

        # 一个sheet页面一个sheet页面读
        # sheetname = reader.get_sheets()
        sheetname = writer.wb.sheetnames

        # print("sheetname为", sheetname)
        '''
        line = reader.readline()[1]
        print("line为", line)
        casetype = line[1]
        '''
        if 'web' in case_file:
            self.obj = Web()
            self.case_type = 'web'
        elif 'app' in case_file:
            self.obj = App()
            self.case_type = 'app'
        else:
            Web().log.info('请在用例文件名中指定是web还是app类型')

        # self.obj = WebUIKeys("CHR")

        # 遍历sheet
        for sheet in sheetname:
            self.sheet = sheet
            # 设置当前读取的sheet页面
            # reader.set_sheet(sheet)
            # 设置大分组名字
            self.feature = sheet
            self.feature_idx += 1
            self.story_idx = 0  # 每个sheet跑完后重新定义模块的顺序
            # lines = reader.readline()
            # lines = reader[sheet]
            lines = ReadExcel().read_excel(case_file, sheet)
            print("打印处lines",lines)
            # self.null_row_num = ReadExcel().null_row_num
            Web().log.info('正在读取到工作表[{}]的所有数据:{}'.format(sheet, lines))
            #统计用例的步骤
            case = []
            # 遍历行
            status = True
            for i in range(0, len(lines)):
                # # 为story加跳过说明，暂时不用
                # if len(lines[i][0])>1 and len(lines[i][9])>1:
                #     lines[i][0] = lines[i][0]+'(跳过)'

                if 'assert' in str(lines[i]):
                    self.i.append(i + 1)
                # print("打印assert所有",self.i)
                line = lines[i]
                # 如果是模块
                if len(line[0])>1:

                    # if len(line[9]) > 1:
                    #     # status = bool(1 - status)
                    #     status = False
                    #     print('status--{}--'.format(status))
                    # else:
                    #     status = True
                    # 如果已经统计完一个用例
                    if case:

                        self.cases.append(case)
                        if i == 1:

                            self.__run_pytest(1)
                            self.i.clear()
                        else:

                            self.__run_pytest()
                            self.i.clear()
                        case = []
                    # if status:
                    # 记住模块的名字
                    self.story = line[0]
                    self.story_idx += 1
                    self.story_row = line

                    # else:
                    #     pass
                # 如果是用例
                elif len(line[1])>1:
                    if case:
                        self.cases.append(case)
                    # 重置case
                    case = []
                    case.append(line)



                # 如果是步骤,原本这里是else
                # elif len(line[1])<1 and status is True:
                else:
                    # 把步骤添加到用例列表里面
                    case.append(line)
            # 保存和运行最后一个模块的用例
            if case:
                self.cases.append(case)
            if self.cases:
                # 执行
                self.__run_pytest(0)
                self.i.clear()
                self.s_idx += 1

        # 最后把代码名字还原
        os.rename('./ddt/test_%s_%s.py' %(self.s_idx - 1, self.c_idx-1), './ddt/test.py')

        #备份
        # os.rename('./test_%s_%s_%s.py' % (self.case_type, self.s_idx - 1, self.c_idx),
        #           '../ddt/test_%s.py' % self.case_type)
        # self.obj.quit()

    def __run_pytest(self, is_start=0):
        '''
        网上有人说：“同一个测试环境的多个执行节点执行同一个用例，测试结果以最后一次执行结果为准，会覆盖掉之前所有别的节点的执行结果，一份测试报告中同一个测试用例的执行结果必须唯一。这是分布式测试的设计机制。”
        :param is_start:
        :return:
        '''
        # 执行用例
        # 刚开始跑第一个用例的时候
        if self.c_idx == 1:
            os.rename('./ddt/test.py', './ddt/test_%s_%s.py'%(self.s_idx,self.c_idx))
            sleep(1)
        else:
            try:
                os.rename('./ddt/test_%s_%s.py'%(self.s_idx, self.c_idx-1), './ddt/test_%s_%s.py'%(self.s_idx, self.c_idx))
                sleep(1)
                # f.flush()  # 强制刷新
                # sleep(5)
            except:
                os.rename('./ddt/test_%s_%s.py'%(self.s_idx-1, self.c_idx-1), './ddt/test_%s_%s.py'%(self.s_idx, self.c_idx))
                sleep(1)

        # os.system('copy .\\test_{}_{}.py .\\test_{}_{}.py'.format(self.s_idx, self.c_idx,self.s_idx, self.c_idx))
        #可以读取刷新，但是依然找不到该文件
        # print("开始读取文件")
        # with open('../ddt/test_{}_{}.py'.format(self.s_idx, self.c_idx), encoding='utf-8') as f:
        #     f.read()
        #     print("可以读取文件test_{}_{}.py".format(self.s_idx, self.c_idx))
        #     print("开始刷新文件")
        #     f.flush()
        #     print("完成刷新文件")
        # print("完成读取文件")

        # print('输出根目录{}'.format(sys.path))
        # import shutil
        # shutil.move('E:\\script\\testingframework\\cases\\excel_ddt.py', 'E:\\script\\testingframework')
        # print('显示当前工作路径{}'.format(os.getcwd()))
        # print('开始切换工作目录')
        # os.chdir(r'E:\script\testingframework')
        # sys.path.append(r'E:\script\testingframework')
        # print('切换后的工作目录{}'.format(os.getcwd()))
        # print('开始复制文件')
        # shutil.copy('./ddt/test_{}_{}.py'.format(self.s_idx, self.c_idx),
        #             'D:\python367\Lib\site-packages')  # 复制文件，都只能是文件
        # print('复制文件后')
        pytest.main(['-s', './ddt/test_{}_{}.py'.format(self.s_idx, self.c_idx), '--alluredir', './report/allure-result','--junitxml', './report/result{}.xml'.format(self.n)])  # 暂时不用self.case_type，在main函数中加'--clean-alluredir'会清空缓存文件，这里也可能加--clean
        # os.system('copy ./environment.properties ./report/allure-result')
        shutil.copyfile('./environment.properties', './report/allure-result/environment.properties')
        self.n += 1
        # os.unlink('../ddt/test.py')
        # shutil.move('E:\\script\\testingframework\\cases\\excel_ddt.py', 'E:\\script\\testingframework')

        # 每执行一个用例，用例的序号加1
        self.c_idx += 1
        self.cases.clear()

        # #备份的
        # def _run_pytest(self, is_start=0):
        #     # 执行用例
        #     # 刚开始跑第一个用例的时候
        #     if self.c_idx == 1:
        #         os.rename('./test_%s.py' % (self.case_type,),
        #                   '../ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx))
        #     else:
        #         try:
        #             os.rename('../ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx),
        #                       '../ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx))
        #         except:
        #             os.rename('../ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx - 1, self.c_idx),
        #                       '../ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx, self.c_idx))
        #
        #     pytest.main(['-s', './test_%s_%s.py' % (self.s_idx, self.c_idx)])  # 暂时不用self.case_type
        #     # 每执行一个用例，用例的序号加1
        #     self.c_idx += 1
        #     self.cases.clear()


    # def runInterCase(self,case_file='.../ddt/test_casess.xlsx',res_file='../'):
    #     # 获取excel里面的用例，处理成列表，并且运行
    #     reader = get_reader(case_file)
    #     # writer = get_writer(case_file,res_file)
    #
    #     # 一个sheet页面一个sheet页面读
    #     sheetname = reader.get_sheets()
    #     self.obj = Inter()
    #     self.case_type = 'inter'
    #     self.s_idx = 1
    #     self.c_idx = 1
    #
    #     ''' 不同的地方
    #     line = reader.readline()[1]
    #     casetype = line[1]
    #     if casetype == 'APP':
    #         self.obj = App()
    #     else:
    #         self.obj = Web()
    #     self.case_type = 'web'''
    #
    #     # 遍历sheet
    #     for sheet in sheetname:
    #         # 设置当前读取的sheet页面
    #         reader.set_sheet(sheet)
    #         # 设置大分组名字
    #         self.feature = sheet
    #         self.feature_idx += 1
    #         self.story_idx = 0
    #         lines = reader.readline()
    #         # 统计用例的步骤
    #         test_casess = []
    #         # 遍历行
    #         for i in range(1, len(lines)):
    #             line = lines[i]
    #             # 如果是模块
    #             if len(line[0]) > 1:
    #                 # 如果已经统计完一个用例
    #                 if test_casess:
    #                     self.cases.append(test_casess)
    #                     # if i == 1:(不一样的地方)
    #                     #     self._run_pytest(1)
    #                     # else:
    #                     self._run_pytest()
    #                     test_casess = []
    #                 # 记住模块的名字
    #                 self.story = line[0]
    #                 self.story_idx += 1
    #             # 如果是用例
    #             elif len(line[1]) > 1:
    #                 if test_casess:
    #                     self.cases.append(test_casess)
    #                 # 重置case
    #                 test_casess = []
    #                 test_casess.append(line)
    #             # 如果是步骤
    #             else:
    #                 # 把步骤添加到用例列表里面
    #                 test_casess.append(line)
    #         # 保存和运行最后一个模块的用例
    #         if test_casess:
    #             self.cases.append(test_casess)
    #         if self.cases:
    #             # 执行
    #             # self._run_pytest(0)不一样的地方
    #             self._run_pytest()
    #             self.s_idx += 1
    #
    #     # 最后把代码名字还原
    #     os.rename('../ddt/test_%s_%s_%s.py' % (self.case_type, self.s_idx - 1, self.c_idx),
    #               '../ddt/test_%s.py' % self.case_type)
    #     # self.obj.quit()不一样的地方

#使用全局变量传参
conf = Conf()

if __name__ == '__main__':
    os.system('rd /s/q result')
    conf.runCase(case_file='../cases/web-testingshop.xlsx')
    # os.system('allure generate ./result/ -o ./report --clean')